package tank

import (
	"github.com/gin-gonic/gin"
	"mime/multipart"
	"net/http"
	"server/config"
	db "server/data"
	"server/utils"
	"strings"
)

type RegMapReq struct {
	Uid     string                `form:"uid" binding:"required"`
	User    string                `form:"user"`
	MapFile *multipart.FileHeader `form:"map" binding:"required"`
}

func RegMap(c *gin.Context) {
	var regMapReq RegMapReq
	if err := c.ShouldBind(&regMapReq); err != nil {
		c.JSON(http.StatusOK, gin.H{"status": http.StatusBadRequest, "desc": err.Error()})
		return
	}

	c.Set(config.RequestLogParamKey, utils.Struct2str(regMapReq))

	uploadDir := config.MapBaseDir + regMapReq.Uid + "/"
	createUploadDirIfNotExists(uploadDir)
	if err := uploadFiles(c, uploadDir, nil, regMapReq.MapFile); err != nil {
		c.JSON(http.StatusOK, gin.H{"status": http.StatusBadRequest, "desc": "upload file error"})
		return
	}

	gameMap := &db.GameMap{
		Uid:     regMapReq.Uid,
		User:    regMapReq.User,
		MapFile: uploadDir + regMapReq.MapFile.Filename,
	}

	mapFile := uploadDir + regMapReq.MapFile.Filename

	if db.DB.Debug().Model(&gameMap).Where("uid = ? and map_file = ?", regMapReq.Uid, mapFile).Updates(&gameMap).RowsAffected == 0 {
		db.DB.Create(&gameMap)
	}

	c.JSON(http.StatusOK, gin.H{
		"status": config.BusinessSuccessCode,
	})
}

type MapResp struct {
	Id      uint
	Uid     string
	MapFile string
}

func Maps(c *gin.Context) {
	var maps []MapResp
	db.DB.Debug().Model(&db.GameMap{}).Select([]string{"id", "uid", "map_file"}).Find(&maps)
	for i := range maps {
		mapFile := maps[i].MapFile
		maps[i].MapFile = mapFile[strings.LastIndex(mapFile, "/")+1 : len(mapFile)] // 截取文件名
	}
	c.JSON(http.StatusOK, gin.H{"status": config.BusinessSuccessCode,
		"maps": maps,
	})
}
